package com.hh.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hh.shiro.dao.UserDao;
import com.hh.shiro.encrypt.Encodes;
import com.hh.shiro.entity.ShiroUser;

public class ShiroDbRealm extends AuthorizingRealm {
	private static final Logger LOGGER = LoggerFactory.getLogger(ShiroDbRealm.class);
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int SALT_SIZE = 8;
	public static final int HASH_INTERATIONS = 1024;

	private UserDao userDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
		if(null == authcToken || null == authcToken.getPrincipal()){
			throw new UnknownAccountException();
		}
		ShiroUser user = null;
		try {
			user = getUserDao().getUserByName(authcToken.getPrincipal().toString());
		} catch (Exception e) {
			LOGGER.info(e.getMessage(),e);
		}
		if (null == user) {
			throw new UnknownAccountException();
		}else{
			byte[] salt = Encodes.decodeHex(user.getSalt());
			return new SimpleAuthenticationInfo(user, user.getPassword(),ByteSource.Util.bytes(salt), getName());
		}
	
		
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
    	ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName())
                .iterator().next();
    	LOGGER.info("shiro user name:", shiroUser.getUsername());
    	return null;
    }
    
    /**设定Password校验的Hash算法与迭代次数.*/
	//@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(HASH_ALGORITHM);
		matcher.setHashIterations(HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
